/**
 * @Description:登录主入口
 * @author 云离
 * @date: 2018/12/28
 */
import React, { Component } from "react";
import { actions } from "../../../../reducers/main";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import {
  message,
  Spin,
  Table,
  Switch,
  Button,
  Icon,
  Pagination,
  Modal,
  Tag
} from "antd";
import MyForm from "../../../components/Form";
import axios from "../../../../apis/api";
import qs from "qs";
import RepayForm from "./RepayForm";
import GroupForm from "../accountGroup";

const { confirm } = Modal;

const mapStateToProps = (state, ownProps) => {
  return {
    vwAgentCashStat: state.main.vwAgentCashStat,
    vwAgentCashDayStat: state.main.vwAgentCashDayStat,
    isAdmin: state.main.isAdmin,
  };
};

const mapDispatchToProps = dispatch => {
  return {
    fetchInitData: next => dispatch(actions.fetchInitData(next))
  };
};

class ChannelOrder extends Component {
  state = {
    initForm: {
      agentUserId: "",
      account: "",
      businessName: "",
      channelUserId: "",
      ptOrderno: "",
      childOrderno: "",
      orderStatus: "",
      "params[beginTime]": "",
      "params[endTime]:": "",
      payType: ""
    },
    formItmes: [],
    searchParam: {},
    loading: false,
    depMap: {},
    pageSize: 10,
    curPage: 1,
    tableData: {
      total: 0,
      rows: []
    },
    channels: [], // 码商代理
    proxys: [], // 商户代理
    payTypes: [], // 支付类型
    payTypesMap: {},
    orderStatusMap: {
      "4": {
        label: "未付款",
        class: "red"
      },
      "3": {
        label: "已成功,未上分",
        class: "volcano"
      },
      "2": {
        label: "手动补单",
        class: "magenta"
      },
      "1": {
        label: "已支付",
        class: "green"
      },
      "0": {
        label: "支付中",
        class: "cyan"
      }
    },
    visibleDlg: false,
    initReplayForm: {},
    repayFormTitle: "补单操作",
    curRepayRow: {},
    confirmLoading: false
  };

  handleSearch = value => {
    this.setState(
      {
        curPage: 1,
        searchParam: value
      },
      this.searchTable
    );
  };

  componentDidMount() {
    this.init();
  }

  init = async () => {
    try {
      this.setState({
        loading: true
      });
      const result = await axios.post("/system/user/salesman");
      const options = result.rows.map(item => {
        return {
          value: item.userId,
          label: item.userName
        };
      });
      this.setState({
        formItmes: [
          {
            label: "业务员",
            key: "agentUserId",
            type: "select",
            options: [{ value: "", label: "所有" }, ...options]
          },
          {
            label: "用户类型",
            key: "bankName",
            type: "select",
            options: [{value: '', label: '所有'},{value: '假人', label: '假人'},{value: '真人', label: '真人'}]
          },
          {
            label: "会员手机号",
            key: "businessName",
            type: "input"
          },
          {
            label: "平台订单号",
            key: "ptOrderno",
            type: "input"
          },
          {
            label: "订单状态",
            key: "orderStatus",
            type: "select",
            options: [
              {
                label: "所有",
                value: ""
              },
              {
                label: "支付中",
                value: "0"
              },
              {
                label: "已支付",
                value: "1"
              },
              {
                label: "手动补单",
                value: "2"
              },
              {
                label: "已成功,未上分",
                value: "3"
              },
              {
                label: "未付款",
                value: "4"
              }
            ]
          },
          {
            label: "创建开始时间",
            key: "params[beginTime]",
            type: "DatePicker"
          },
          {
            label: "创建结束时间",
            key: "params[endTime]",
            type: "DatePicker"
          }
        ]
      });
      this.searchTable();
      this.setState({
        loading: false
      });
    } catch (e) {
      this.setState({
        loading: false
      });
      message.error(e.message);
    }
  };

  searchTable = async () => {
    const { pageSize, curPage, searchParam } = this.state;
    const query = {
      orderByColumn: "submitTime",
      isAsc: "desc",
      pageSize,
      pageNum: curPage,
      "params[beginTime]":
        (searchParam.params &&
          searchParam.params.beginTime &&
          searchParam.params.beginTime.format("YYYY-MM-DD")) ||
        "",
      "params[endTime]":
        (searchParam.params &&
          searchParam.params.endTime &&
          searchParam.params.endTime.format("YYYY-MM-DD")) ||
        "",
      agentUserId: searchParam.agentUserId,
      account: searchParam.account,
      businessName: searchParam.businessName,
      ptOrderno: searchParam.ptOrderno,
      orderStatus: searchParam.orderStatus,
      bankName: searchParam.bankName
    };
    try {
      this.setState({
        loading: true
      });
      const result = await axios.post(
        "/channel/channelOrder/list",
        qs.stringify(query)
      );
      if (result.code === 0) {
        this.setState({
          tableData: result,
          loading: false
        });
      } else {
        this.setState({
          loading: false
        });
        message.error(result.msg);
      }
    } catch (e) {
      this.setState({
        loading: false
      });
      message.error(e.message);
    }
  };
  //翻页
  handlePageChange = (page, pageSize) => {
    this.setState(
      {
        curPage: page
      },
      this.searchTable
    );
  };
  //补单
  replay = data => {
    this.setState({
      visibleDlg: true,
      initReplayForm: Object.assign({}, data, {
        amount: data.orderAmount || 0.01,
        code: ""
      }),
      curRepayRow: data
    });
  };

  submitRepayForm = async data => {
    const { curRepayRow } = this.state;
    try {
      this.setState({
        confirmLoading: true
      });
      const result = await axios.post(
        "/channel/channelOrder/edit",
        qs.stringify({
          ...data,
          orderId: curRepayRow.orderId,
          businessId: curRepayRow.businessId,
          channelUserId: curRepayRow.channelUserId
        })
      );
      if (result.code === 0) {
        message.success(result.msg);
        this.cancelRepayForm();
        this.handlePageChange(1);
      } else {
        message.error(result.msg);
      }
      this.setState({
        confirmLoading: false
      });
    } catch (e) {
      this.setState({
        confirmLoading: false
      });
      console.log(e);
    }
  };

  cancelRepayForm = async () => {
    this.setState({
      visibleDlg: false,
      confirmLoading: false
    });
  };

  onShowSizeChange = (current, pageSize) => {
    this.setState(
      {
        pageSize: pageSize,
        curPage: current
      },
      this.searchTable
    );
  };

  render() {
    const {
      initForm,
      formItmes,
      loading,
      tableData,
      curPage,
      pageSize,
      orderStatusMap
    } = this.state;
    const { isAdmin } = this.props;
    const columns = [
      {
        title: "平台订单号",
        dataIndex: "ptOrderno",
        key: "ptOrderno"
      },
      {
        title: "会员手机号",
        dataIndex: "businessName",
        key: "businessName"
      },
      {
        title: "用户类型",
        dataIndex: "bankName",
        key: "bankName",
        render: text => {
          return text === "假人" ? (
            <Tag color="#f50">假人</Tag>
          ) : (
            <Tag color="#108ee9">真人</Tag>
          );
        }
      },
      {
        title: "手动上分",
        dataIndex: "ddId",
        key: "ddId",
        render: text => {
          return text === 1 ? (
            <Tag color="#f50">手动上分</Tag>
          ) : (
            <Tag color="#87d068">正常订单</Tag>
          );
        }
      },
      {
        title: "业务员",
        dataIndex: "agentUserName",
        key: "agentUserName"
      },
      {
        title: "实际金额",
        dataIndex: "payAmount",
        key: "payAmount"
      },
      {
        title: "创建日期",
        dataIndex: "submitTime",
        key: "submitTime"
      },
      {
        title: "成功日期",
        dataIndex: "successTime",
        key: "successTime"
      },
      {
        title: "交易账号",
        dataIndex: "account",
        key: "account"
      },
      {
        title: "状态",
        dataIndex: "orderStatus",
        key: "orderStatus",
        fixed: "right",
        render: (value, data) => {
          return (
            <Tag color={orderStatusMap[value].class}>
              {orderStatusMap[value].label}
            </Tag>
          );
        }
      }
    ];
    if (isAdmin) {
      columns.push({
        title: "操作",
        dataIndex: "actions",
        key: "actions",
        fixed: "right",
        render: (value, data) => {
          if(data.orderStatus === '0') {
            return (
                <Button
                    size={"small"}
                    type="primary"
                    onClick={() => this.replay(data)}
                >
                  补单
                </Button>
            );
          }
        }
      });
    }
    return (
      <div>
        <MyForm
          initForm={initForm}
          items={formItmes}
          handleSearch={this.handleSearch}
        />
        <Spin spinning={loading}>
          <Table
            dataSource={tableData.rows}
            columns={columns}
            pagination={false}
            scroll={{ x: true }}
          />
          <Pagination
            style={{ marginTop: 10, marginBottom: 20 }}
            total={tableData.total}
            showTotal={total => `共 ${total} 项`}
            pageSizeOptions={["10", "20", "50", "100", "500"]}
            showSizeChanger
            onShowSizeChange={this.onShowSizeChange}
            pageSize={pageSize}
            current={curPage}
            onChange={this.handlePageChange}
          />
        </Spin>
        <RepayForm
          confirmLoading={this.state.confirmLoading}
          visible={this.state.visibleDlg}
          initForm={this.state.initReplayForm}
          title={this.state.repayFormTitle}
          okCb={this.submitRepayForm}
          cancelCb={this.cancelRepayForm}
        />
      </div>
    );
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(ChannelOrder));
